package dk.pervasivepositioning.project2;

import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;

public abstract class ReportingStrategy {
	protected Activity activity;
	protected LocationManager lm;
	private final HTTPSender sender;
	private final Executor executor = Executors.newSingleThreadExecutor();
	protected LocationListener listener = new LocationListener() {

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}

		public void onProviderEnabled(String provider) {
		}

		public void onProviderDisabled(String provider) {
		}

		public void onLocationChanged(Location location) {
			try {
				printToFile(location);
				receivedLocation(location);
				printDebugInfo("GPS FIX RECEIVED: "
						+ System.currentTimeMillis() + "\n");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	};
	private int fixes = 0;

	public ReportingStrategy(String URL) throws IOException {
		sender = new HTTPSender(URL);
	}

	public abstract void startup();

	public void sendData(final Location location)
			throws IOException {
		executor.execute(new Runnable() {

			public void run() {
				try {
					sender.sendData(location, getStrategy());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					printDebugInfo(e.getMessage());
				}

			}
		});
		printDebugInfo("SENDING DATA \n");
	}

	protected void startUpdates() {
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
	}

	protected void printToFile(Location location) throws IOException {
		((TextView) activity.findViewById(R.id.gps_fixes))
				.setText("GPS FIXES: " + ++fixes);
	}

	public abstract void receivedLocation(Location location) throws IOException;

	public void shutdown() {
		lm.removeUpdates(listener);
	}

	public void stopUpdates() {
		lm.removeUpdates(listener);
	}

	public void printDebugInfo(String s) {
		TextView text = (TextView) activity
				.findViewById(R.id.what_is_happening);
		text.setText(s + text.getText());
	}
	
	public abstract String getStrategy();

}
